package priv.lhy.utils;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * author : lihy
 * date : 2019/1/23 15:09
 * <p>
 * cookie工具类
 */
public class CookieUtils {

    /**
     * 获取cookie值
     *
     * @param request
     * @param key
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if (ArrayUtils.isNotEmpty(cookies)) {
            for (Cookie cookie : cookies) {
                if (StringUtils.equals(cookie.getName(), key)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    /**
     * 生成cookie根节点
     *
     * @param key
     * @param value
     * @param maxAge
     * @param domain
     * @return
     */
    public static Cookie rootCookieWithDomain(String key, String value, int maxAge, String domain) {
        return rootCookie(key, value, "/", maxAge, domain);
    }

    /**
     * 生成cookie节点
     *
     * @param key
     * @param value
     * @param uri
     * @param maxAge
     * @param domain
     * @return
     */
    public static Cookie rootCookie(String key, String value, String uri, int maxAge, String domain) {
        Cookie cookie = new Cookie(key, value);
        enrichCookie(cookie, uri, maxAge, domain);
        return cookie;
    }

    /**
     * 设置cookie
     *
     * @param response
     * @param cookie
     */
    public static void setCookie(HttpServletResponse response, Cookie cookie) {
        response.addCookie(cookie);
    }

    /**
     * 判断是否为AJAX请求
     *
     * @param request
     * @return
     */
    public static boolean isAjax(HttpServletRequest request) {
        boolean isAjaxRequest = false;
        //判断是否为异步请求，是则为AJAX请求
        if (!StringUtils.isBlank(request.getHeader("x-requested-with")) && request.getHeader("x-requested-with").equals("XMLHttpRequest")) {
            isAjaxRequest = true;
        }
        return isAjaxRequest;
    }

    /**
     * 填充cookie
     *
     * @param cookie
     * @param uri
     * @param maxAge
     * @param domain
     */
    private static void enrichCookie(Cookie cookie, String uri, int maxAge, String domain) {
        cookie.setPath(uri);
        cookie.setMaxAge(maxAge);
        cookie.setDomain(domain);
    }
}
